package com.xiyun.easyapi.service;

import apijson.RequestMethod;
import apijson.StringUtil;
import cn.hutool.json.JSONUtil;
import com.xiyun.easyapi.annotation.CustomLog;
import com.xiyun.easyapi.config.apijson.SqlParser;
import com.xiyun.easyapi.config.constant.Code;
import com.xiyun.easyapi.config.util.Res;
import com.xiyun.easyapi.config.web.CustomException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * API服务类
 */
@Service
@CustomLog
@SuppressWarnings("all")
public class ApiService {

    /**
     * 重写newParser方法，设置不需要验证
     *
     * @param session HttpSession对象
     * @param method  请求方法
     * @return Parser对象
     */
    public String parse(RequestMethod method, String request, HttpSession session) {
        return new SqlParser(method).setSession(session).setNeedVerify(false).parse(request);
    }

    /**
     * 重写json方法，返回Res对象
     *
     * @param method  请求方法
     * @param request 请求json
     * @param session HttpSession对象
     * @return Res对象
     */
    public Res<?> json(String method, String request, HttpSession session) {
        String json = parse(RequestMethod.valueOf(StringUtil.toUpperCase(method)), request, session);
        Map<String, ?> map = JSONUtil.toBean(json, Map.class);
        int code = Integer.parseInt(map.get("code")
                .toString());
        String msg = map.get("msg")
                .toString();
        map.remove("code");
        map.remove("msg");
        map.remove("ok");
        if (code == 401) throw new CustomException("对象不存在");
        return Res.builder()
                .code(new Code(code, msg))
                .body(map)
                .build();
    }
}

